﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.DDSolutions.SqlReportServer;

namespace Microsoft.DDSolutions.SqlReportServer
{
    public sealed class ReportServiceFactory
    {
        private static ReportServiceFactory instance = new ReportServiceFactory();

        private ReportServiceFactory() { }

        public static ReportServiceFactory Instance
        {
            get { return instance; }
        }

        public static IReportService CreateReportService(string url)
        {
            IReportService rs;


            // SSRS 2008 has a different web service so we need to 
            // determine the SSRS version and act appropriately.
            int ssrsVerMajor = GetSSRSVersion(url);
            if (ssrsVerMajor == 10)
            {
                url = url.Replace("ReportService.asmx", "ReportService2005.asmx");
                rs = new ReportingService2008Proxy(url);
            }
            else
            {
                rs = new ReportingServiceProxy(url);
            }
                            

            return rs;

        }
        private static int GetSSRSVersion(string rsUrl)
        {
            int majorVer = 0;

            // Call the ReportServer root to get a directory listing that returns the SSRS version
            string reportServerUrl = rsUrl.Substring(0, rsUrl.LastIndexOf("/"));
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(reportServerUrl);
            myRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            myRequest.Method = "GET";
            WebResponse myResponse = myRequest.GetResponse();
            StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            string result = sr.ReadToEnd();
            sr.Close();
            myResponse.Close();

            Regex v = new Regex(@"(?<ver>\d*\.\d*\.\d*\.\d*)");
            Match m = v.Match(result);

            if (m.Success)
            {
                string[] vers = m.Value.Split(new char[] { '.' });
                int foundMajor = 0;
                if (vers.Length > 0 && int.TryParse(vers[0], out foundMajor))
                {
                    majorVer = foundMajor;
                }
            }

            return majorVer;
        }

    }
}
